import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import ws.*;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.handler.MessageContext;

public class LoginBean {

    private String name;
    private String password;

    public LoginBean() {
    }

    public Boolean getLoggedIn() {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        if (session.getAttribute("User") != null) {
            return true;

        } else {
            return false;
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String validate() {
        ws.RoMaWS_Service service = new ws.RoMaWS_Service();
        ws.RoMaWS port = service.getRoMaWSPort();
        
        Map<String, Object> req_ctx = ((BindingProvider)port).getRequestContext();
        req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WSUrl.wsUrl);
        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        headers.put("Username", Collections.singletonList(name));
        headers.put("Password", Collections.singletonList(password));
        req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
        
        UserUI user = port.validateUser(name, password);

        if (user != null) {
            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
            session.setAttribute("User", user);
            //loggedIn = true;
            return "true";
        }
        return "false";
    }

    public String logout() {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        session.setAttribute("User", null);
        name = "";
        password = "";
        return "true";
    }
}
